"""
File: utils.py
Author: ershixiong
Date: 2023/12/12
describe:

"""
import json
import os

import jsonschema
import pymysql
import yaml
from genson import SchemaBuilder


class Utils:
    # 类方法不需要实例化就可以调用
    @classmethod
    def get_yaml_data(cls, file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            datas = yaml.safe_load(f)
            return datas

    @classmethod
    def get_json_data(cls, file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            datas = json.load(f)
            return datas

    @classmethod
    def get_root_dir(cls):
        return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    @classmethod
    def generate_schema(cls, obj, file_path):
        """
        生成schema文件
        """
        builder = SchemaBuilder()
        # 把预期的响应值添加到builder中
        builder.add_schema(obj)
        # 生成json schema
        schema_content = builder.to_schema()
        print(schema_content)
        # 写入json文件
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(schema_content, f)

    @classmethod
    def schema_validate(cls, obj, schema):
        """
        对比python对象与生成的 json schema结构是否一致
        :param obj:
        :param schema:
        :return:
        """
        try:
            jsonschema.validate(obj,schema)
            return True
        except Exception as e:
            print(f'schema校验异常======>{e}')
            return False

    @classmethod
    def query_db(cls, sql, database_info):
        # 连接数据库
        conn = pymysql.Connect(**database_info)
        # 创建游标
        cursor = conn.cursor()
        # 执行 SQL 语句
        print(f"要执行的 sql 语句：{sql}")
        cursor.execute(sql)
        # 获取查询结果
        datas = cursor.fetchall()
        print("查询到的数据为:", datas)  # 获取多条数据
        # 关闭连接
        cursor.close()
        conn.close()
        return datas